﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraTurn : MonoBehaviour
{
    [SerializeField] private Vector3 m_defaultInternal;

    private Vector3 m_localTargetPosition;

    private Vector3 m_velocity;

    private Vector3 m_localPosition;

    private Transform m_transform;

    [SerializeField] private Transform m_lookAtTransform;

    [SerializeField] private float m_rotateSpeed;

    [SerializeField] private float m_smoothTime;

    [SerializeField] private float m_resetSpeed;

    private bool m_isReset;

    // Use this for initialization
    void Start()
    {
        EventMgr.AddEventListener(GameTypeDefine.EVENT_ID.CAMERA_TURN, TurnCamera);
        EventMgr.AddEventListener(GameTypeDefine.EVENT_ID.CAMERA_RESET, ResetCamera);

        m_transform = this.transform;

        m_transform.position = m_lookAtTransform.position + m_defaultInternal;
    }

    // Update is called once per frame
    void Update()
    {
        if (m_isReset)
        {
            m_localPosition = m_lookAtTransform.InverseTransformPoint(m_transform.position);
            m_localTargetPosition = m_lookAtTransform.InverseTransformPoint(m_lookAtTransform.position + m_defaultInternal);

            var tempPosition = new Vector3(m_localPosition.x, 0, m_localPosition.z);
            m_localTargetPosition.Set(m_localTargetPosition.x, 0, m_localPosition.z);

            float direct = Vector3.Cross(tempPosition, m_localTargetPosition).y;

            float speed = -m_resetSpeed;
            if (direct > 0)
            {
                speed = m_resetSpeed;
            }

            tempPosition = MyMath.Cycle(tempPosition, m_lookAtTransform.up, speed);

            if (Vector3.Cross(tempPosition, m_localTargetPosition).y * direct < 0)
            {
                m_transform.position = m_lookAtTransform.position + m_defaultInternal;
                m_isReset = false;
            }
            else
            {
                m_localPosition.Set(tempPosition.x, m_localPosition.y, tempPosition.z);
                m_transform.position = m_lookAtTransform.TransformPoint(m_localPosition);
            }
        }

        m_transform.LookAt(m_lookAtTransform);
    }

    public void TurnCamera(GameTypeDefine.EVENT_ID id, MyEventArgs args)
    {
        m_isReset = false;

        float tempRad = ((DegreeEventArgs)args).Degree * m_rotateSpeed;

        m_transform.RotateAround(m_lookAtTransform.position, m_lookAtTransform.up, tempRad);
    }

    public void ResetCamera(GameTypeDefine.EVENT_ID id, MyEventArgs args)
    {
        if ((m_transform.position - m_lookAtTransform.position - m_defaultInternal).sqrMagnitude < 0.01f)
        {
            return;
        }

        m_isReset = true;
    }
}
